package com.tsd.jxc.stock.service.impl;

import com.tsd.common.vo.BatchDeleteLogicVo;
import com.tsd.core.thread.ThreadPoolTaskUtil;
import com.tsd.core.utils.DoubleUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.stock.dao.JxcStockInventoryItemMapper;
import com.tsd.jxc.stock.dao.JxcStockInventoryMapper;
import com.tsd.jxc.stock.entity.JxcStockInventoryExt;
import com.tsd.jxc.stock.entity.JxcStockInventoryItem;
import com.tsd.jxc.stock.entity.JxcStockInventoryItemExt;
import com.tsd.jxc.stock.service.JxcStockGoodsService;
import com.tsd.jxc.stock.service.JxcStockInventoryItemService;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：JxcStockInventoryItem 服务实现层
 *
 * @author Hillpool
 * @date 2022/07/29 15:06:33
 */
@Service
public class JxcStockInventoryItemServiceImpl extends BaseServiceImpl implements JxcStockInventoryItemService {

    @Resource
    private JxcStockInventoryItemMapper jxcStockInventoryItemMapper;
    @Resource
    private JxcStockInventoryMapper jxcStockInventoryMapper;
    @Resource
    private JxcStockGoodsService jxcStockGoodsService;

    @Override
    public JxcStockInventoryItem getJxcStockInventoryItemById(Long id) throws Exception {
        return jxcStockInventoryItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public JxcStockInventoryItemExt queryBySid(String sid) throws Exception {
        return jxcStockInventoryItemMapper.selectBySid(sid);
    }

    @Override
    public List<JxcStockInventoryItemExt> queryByInventoryList(List<String> inventory_list) throws Exception {
        return ThreadPoolTaskUtil.queryInList4Split(inventory_list, list -> {
            JxcStockInventoryItemExt params = new JxcStockInventoryItemExt();
            params.setDr(0);
            params.setInventory_list(list);
            return jxcStockInventoryItemMapper.selectByEntity(params);
        });
    }

    @Override
    public void deleteJxcStockInventoryItems(List<String> list, SysUser opUser) throws Exception {
        for (String sid : list) {
            JxcStockInventoryItem old = jxcStockInventoryItemMapper.selectBySid(sid);
            super.checkEmpty(old, "该记录不存在");
            super.autoInjectBaseData(old, opUser, TYPE_DELETE);
            jxcStockInventoryItemMapper.updateByPrimaryKeySelective(old);
        }
    }

    @Override
    public void saveJxcStockInventoryItem(JxcStockInventoryItem record, SysUser opUser) throws Exception {
        if (HlpUtils.isEmpty(record.getId())) {
            super.autoInjectBaseData(record, opUser, this.TYPE_CREATE);
            jxcStockInventoryItemMapper.insertSelective(record);
        } else {
            super.autoInjectBaseData(record, opUser, this.TYPE_UPDATE);
            jxcStockInventoryItemMapper.updateByPrimaryKeySelective(record);
        }
    }

    @Override
    public void batchSaveJxcStockInventoryItem(List<JxcStockInventoryItemExt> list, SysUserExt opUser) throws Exception {
        if (HlpUtils.isEmptyList(list)) {
            return;
        }
        JxcStockInventoryItem item = jxcStockInventoryItemMapper.selectByPrimaryKey(list.get(0).getId());
        if (item == null) {
            return;
        }
        JxcStockInventoryExt inventoryExt = jxcStockInventoryMapper.selectBySid(item.getInventory_sid());
        super.checkEmpty(inventoryExt, "盘点单不存在");
        if (1 == inventoryExt.getUpdate_stock()) {
            throw new HlpException("盘点单：" + inventoryExt.getCode() + " 已更新库存");
        }
        List<JxcStockInventoryItemExt> updateList = ListUtil.filter(list, t -> !HlpUtils.isEmpty(t.getId()));
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList4Split(updateList, false, itemList -> jxcStockInventoryItemMapper.updateList(itemList));
        }
    }

    @Override
    public List<JxcStockInventoryItemExt> findJxcStockInventoryItems(Map<String, Object> params, PageBean page) throws Exception {
        return jxcStockInventoryItemMapper.selectByPage(params, page);
    }

    @Override
    public List<JxcStockInventoryItemExt> findJxcStockInventoryItems(Map<String, Object> params) throws Exception {
        return jxcStockInventoryItemMapper.selectByParams(params);
    }

    @Override
    public List<JxcStockInventoryItemExt> queryGoodsByInventoryIdByPage(Map<String, Object> params, PageBean page) {
        return jxcStockInventoryItemMapper.selectGoodsByInventoryIdByPage(params, page);
    }

    @Override
    public List<JxcStockInventoryItemExt> queryGoodsByInventoryId(Map<String, Object> params) {
        return jxcStockInventoryItemMapper.selectGoodsByInventoryId(params);
    }

    @Override
    public void saveJxcStockInventoryDetail(JxcStockInventoryExt record, SysUser opUser) throws Exception {
        List<JxcStockInventoryItemExt> itemList = record.getItem_list();
        super.checkEmptyList(itemList, "盘点明细不能为空");

        List<Long> existIdList = ListUtil.filterMap(itemList, t -> !HlpUtils.isEmpty(t.getId()), JxcStockInventoryItemExt::getId);

        JxcStockInventoryItemExt params = new JxcStockInventoryItemExt();
        params.setDr(0);
        params.setInventory_sid(record.getSid());
        List<JxcStockInventoryItemExt> oldList = jxcStockInventoryItemMapper.selectByEntity(params);

        //删除不存在订单明细
        List<Long> delIds = ListUtil.filterMap(oldList, t -> !existIdList.contains(t.getId()), JxcStockInventoryItemExt::getId);
        if (!HlpUtils.isEmptyList(delIds)) {
            BatchDeleteLogicVo logicVo = new BatchDeleteLogicVo(opUser);
            logicVo.setIdList(delIds);
            jxcStockInventoryItemMapper.deleteLogicByIdList(logicVo);
        }

        List<JxcStockInventoryItemExt> insertList = new ArrayList<>();
        List<JxcStockInventoryItemExt> updateList = new ArrayList<>();
        for (JxcStockInventoryItemExt itemExt : itemList) {
            itemExt.setInventory_sid(record.getSid());
            double surplus = DoubleUtil.sub(itemExt.getCheck_qty(), itemExt.getOld_qty());
            itemExt.setSurplus(BigDecimal.valueOf(surplus).intValue());
            if (HlpUtils.isEmpty(itemExt.getId())) {
                super.autoInjectBaseData(itemExt, opUser, this.TYPE_CREATE);
                insertList.add(itemExt);
            } else {
                super.autoInjectBaseData(itemExt, opUser, this.TYPE_UPDATE);
                updateList.add(itemExt);
            }
        }
        if (!HlpUtils.isEmptyList(updateList)) {
            ThreadPoolTaskUtil.executeInList4Split(updateList, false, list -> jxcStockInventoryItemMapper.updateList(list));
        }
        if (!HlpUtils.isEmptyList(insertList)) {
            ThreadPoolTaskUtil.executeInList4Split(insertList, false, list -> jxcStockInventoryItemMapper.insertList(list));
        }
    }

    @Override
    public void checkJxcStockInventoryItem(List<Map> record, SysUser opUser) throws Exception {
        for (Map item : record) {
            String sid = item.get("sid").toString();
            Integer check_qty = Integer.parseInt(item.get("check_qty").toString());
            Integer old_qty = Integer.parseInt(item.get("old_qty").toString());
            if (!HlpUtils.isEmpty(sid)) {
                JxcStockInventoryItemExt jxcStockInventoryItemExt = this.queryBySid(sid);
                if (!HlpUtils.isEmpty(jxcStockInventoryItemExt)) {
                    jxcStockInventoryItemExt.setCheck_qty(BigDecimal.valueOf(check_qty));
                    jxcStockInventoryItemExt.setSurplus(check_qty - old_qty);
                    this.saveJxcStockInventoryItem(jxcStockInventoryItemExt, opUser);
                }
            }
        }
    }

    @Override
    public List<JxcStockInventoryItemExt> selectGoodsBySurplus(String inventory_sid, List<String> record, PageBean page) {
        Map<String, Object> params = new HashMap<>(8);
        params.put("inventory_sid", inventory_sid);
        params.put("dr", 0);
        if (record.size() != 0) {
            if (record.size() == 2) {
                params.put("surplus", 2);
            } else if (record.size() == 1) {
                if ("盘盈".equals(record.get(0)))
                    params.put("surplus", 1);
                else
                    params.put("surplus", -1);
            }
        } else
            params.put("surplus", 0);
        return jxcStockInventoryItemMapper.selectGoodsByInventoryIdByPage(params, page);
    }
}